package com.pk;

import android.util.Log;

import java.net.*;
import android.app.*;
import android.os.*;
import org.json.*;
import android.widget.*;
import android.database.sqlite.*;
import android.database.*;
import android.content.Context;
import java.util.*;
import java.io.*;
import android.view.*;
import org.apache.http.*;
import org.apache.http.impl.client.*;
import org.apache.http.client.methods.*;
import android.content.*;
import java.util.*;
import android.media.MediaPlayer;

import org.apache.http.client.*;

public class Cache {
    Random generator = new Random();
    String storagePath;

    List <Dictionary> test = new ArrayList<Dictionary>();
    Integer I = 1; // wylosowane słówko
    
    private static final Cache INSTANCE = new Cache();
    static String baseURL = "http://supersheep.eu/";

    private Cache() {
        File externalStorage = Environment.getExternalStorageDirectory();
        storagePath = externalStorage.getAbsolutePath()+"/supersheep.eu/";

        // w pliku /base_data

        // ogowanie do serwisu, pobranie wersji aplikacji oraz wersji bazy danych
        // jesli jest starsza to czyszczenie na bierzaco cache

        /*Bundle baseBundleData = new Bundle();

        baseBundleData.putString("sd", "");
        String base_data = this.getResource("dict/loading");
        Log.d("rr", base_data); */
    }
    public static Cache getInstance() {
        return INSTANCE;
    }

    public String getResource (String arg) {
        return get(baseURL+arg);
    }
    /**
     * funkcja pobiera zasob (json/xml) z internetu zapamietuje go i zwraca dane
     * @param url adres zasobu
     * @return
     */
    public String get (String url){
        String response = "";
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse execute = client.execute(httpGet);
            InputStream content = execute.getEntity().getContent();
            BufferedReader buffer = new BufferedReader( new InputStreamReader(content));
            String s = "";
            while ((s = buffer.readLine()) != null) {
                    response += s;
            }
        } catch (Exception e) { }
        return response;
    }

    public void playAudio (String url) {
        try {
            MediaPlayer mp = new MediaPlayer();
            mp.setDataSource(url);
            mp.prepare();
            mp.start();
        } catch (Exception e) {  }
    }

    /**
     * losuje slowko z z testu
     */
    public void randTid () {
        I = generator.nextInt(test.size());
    }

    public String readFile (String name, Integer id) {
        // /sdcard/supersheep.eu/name/id


        File file = new File("C:\\MyFile.txt");
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        DataInputStream dis = null;

        try {
            fis = new FileInputStream(file);

            // Here BufferedInputStream is added for fast reading.
            bis = new BufferedInputStream(fis);
            dis = new DataInputStream(bis);

            // dis.available() returns 0 if the file does not have more lines.
            while (dis.available() != 0) {
                System.out.println(dis.readLine());
            }

            // dispose all the resources after using them.
            fis.close();
            bis.close();
            dis.close();

        } catch (FileNotFoundException e) {
            //e.printStackTrace();
        } catch (IOException e) {
            //e.printStackTrace();
        }
        return "";
    }

    public void writeFile (String name, Integer id, String stringFile) {
               // Create file
        try {
            FileWriter fstream = new FileWriter(storagePath+name+"/"+id);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(stringFile);
            out.close();
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }

    public void getTid (int id) {
        // sprawdzam czy dany test jest zapisany
        // na dysku 
        // String json = readFile("tid",id);
        // SuperSheep

        try {
            JSONObject rek;
            String json = get(baseURL+"dict/tid/"+id);
            JSONArray testJSON = (JSONArray) new JSONTokener(json).nextValue();
            for (int i=0;i<testJSON.length();i++) {
                rek = (JSONObject) testJSON.get(i);
                Dictionary <String,Object> dictRec = new Hashtable<String,Object>();
                dictRec.put("from", rek.getString("from"));
                dictRec.put("to", rek.getString("to"));
                dictRec.put("id", rek.getInt("id"));
                test.add(dictRec);
            }
        } catch (JSONException e) {
            // błąd parsowanie json
        }
    }
    
    /**
     * @return aktualnie pytane słówko
     */
    public String getFrom () {
        Dictionary rec = test.get(I);
        return (String) rec.get("from");

    }
    
    /**
     * @return aktualnie pytane słówko
     */
    public String getTo () {
        Dictionary rec = test.get(I);
        return (String) rec.get("to");

    }
    public void store (String hash) {
       
    }
}
